package cn.xawl.interview.thread;

import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lh
 * @date 2020/08/24 14:35:42
 **/
public class CASDemo {

    public static void main(String[] args) throws NoSuchFieldException {
        AtomicInteger atomicInteger = new AtomicInteger(5);//设置初始值为5，也就是主内存保存的值为5

        //此时main线程的预期值为5，如果和主内存中的值比较后相同，就将值修改为update值2020
        System.out.println(atomicInteger.compareAndSet(5, 2020) + "\t current value:" + atomicInteger.get());
        //由于上一步操作成功将主内存的值修改为2020，而此时的预期值还是5，因此主内存中的值不会被修改，还会是2020
        System.out.println(atomicInteger.compareAndSet(5, 2048) + "\t current value:" + atomicInteger.get());
        atomicInteger.getAndIncrement();
        Unsafe unsafe = Unsafe.getUnsafe();
        unsafe.getAndAddInt(atomicInteger, unsafe.objectFieldOffset(AtomicInteger.class.getField("value")), -1);
    }

}
